package threadConn;

import java.util.ArrayList;

/**
 * Created by brossdong on 2018/1/17.
 * 线程间通信
 * 使用wait和notify
 */
public class ConnThread {

    private static ArrayList list = new ArrayList();

    public void add() {
        list.add("brossdong");
    }

    public int getSize() {
        return list.size();
    }

    public static void main(String[] args) {

        final ConnThread connThread = new ConnThread();
        //实例化一个锁
        final Object lock = new Object();

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                try {
                    synchronized (lock) {
                        for (int i = 0;i < 10;i++) {
                            connThread.add();
                            System.out.println("当前线程:" + Thread.currentThread().getName() + "添加了一个元素...");
                            Thread.sleep(500);
                            if (connThread.getSize() == 5) {
                                System.out.println("发出通知...");
                                lock.notify();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"t1");

        Thread t2 = new Thread(new Runnable() {
            public void run() {

                    synchronized (lock) {
                        try {
                            if (connThread.getSize() != 5) {
                                lock.wait();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println("当前线程:" + Thread.currentThread().getName() + "收到线程通知,停止...");
                        throw new RuntimeException();
                    }
            }
        },"t2");
        t2.start();
        t1.start();

    }

}
